<template>
  <div class="sign_in register_wrap">
    <div class="card-wrapper">
		<div class="left"></div>
		<div class="right">
			<div class="title">注册</div>
			<el-form
						  :model="form"
						  label-width="80px"
						  class="login-form"
						  ref="ruleFormRef"
						  :rules="rules"
					  >
						<el-form-item label="身份" prop="user_group">
						  <el-radio-group v-model="form.user_group">
							<el-radio
								v-for="(o, i) in list_user_group"
								:key="i"
								:value="o"
								:label="o"
							>{{ o }}
							</el-radio
							>
						  </el-radio-group>
						</el-form-item>
						<el-form-item label="账号" prop="username">
						  <el-input type="text" v-model="form.username" placeholder="账号">
						  </el-input>
						</el-form-item>
			
						<el-form-item label="密码" prop="password">
						  <el-input
							  type="password"
							  v-model="form.password"
							  placeholder="5 到 16 个字符"
							  autocomplete="new-password"
						  >
						  </el-input>
						</el-form-item>
			
						<el-form-item label="确认密码" prop="confirm_password">
						  <el-input
							  type="password"
							  v-model="form.confirm_password"
							  placeholder="5 到 16 个字符"
							  autocomplete="new-password"
						  >
						  </el-input>
						</el-form-item>
			
						<el-form-item label="昵称" prop="nickname">
						  <el-input type="text" v-model="form.nickname" placeholder="昵称">
						  </el-input>
						</el-form-item>
			
						<el-form-item label="邮箱" prop="email">
						  <el-input
							  type="email"
							  v-model="form.email"
							  placeholder="例：test@test.com!"
						  >
						  </el-input>
						</el-form-item>
									<el-form-item label="头像" prop="avatar">
						  <el-upload
							  id="avatar"
							  class="avatar-uploader"
							  drag
							  accept="image/gif, image/jpeg, image/png, image/jpg"
							  action=""
							  :http-request="uploadimg"
							  :show-file-list="false"
						  >
							<img
								v-if="form['avatar']"
								:src="$fullUrl($banseUrl, form['avatar'])"
								class="avatar"
							/>
							<div v-else>
							  <el-icon class="el-icon--upload">
								<upload-filled/>
							  </el-icon>
							  <div class="el-upload__text">
								<em>点击</em> 或将文件拖拽到这里上传
							  </div>
							</div>
							<template #tip>
							  <div class="el-upload__tip">
								支持扩展名：image/gif, image/jpeg, image/png, image/jpg
							  </div>
							</template>
						  </el-upload>
						</el-form-item>
						
						  						<!-- 注册用户 -->
						<form_registered_user
								v-if="form.user_group == '注册用户'"
								v-model:form="form_sub"
						></form_registered_user>
			  						  						<!-- 商家用户 -->
						<form_merchant_users
								v-if="form.user_group == '商家用户'"
								v-model:form="form_sub"
						></form_merchant_users>
			  						  						  						  						  						  						  						  						  						  								  </el-form>
					  <div class="button-wrapper">
					    <el-button
					      class="button"
					      type="primary"
					      @click="Onsubmit()"
					      >注册</el-button
					    >
					    <el-button
					      @click="router.push('/')"
					      class="button"
					      type="primary"
					      >返回登录</el-button
					    >
					  </div>
		</div>
    </div>
  </div>
</template>

<script setup>
  import {ref, onMounted} from "vue";
  import { $post, $get } from "@/api/Api.js";
  import {useStore} from "vuex";
  import {useRouter, useRoute} from "vue-router";
  import { $fullUrl, $banseUrl,$get_stamp,$get_rand,$is_phone,$is_tel,$is_email } from "@/utils/utils.js";

  let router = useRouter();
  let route = useRoute();
  let store = useStore();
  let oauth = ref({
    signIn: false,
  });
  let url_submit = ref("/api/user/register");
  let url_upload = ref("/api/user/upload");
  let form = ref({
    username: "",
    password: "",
    nickname: "",
    confirm_password: "",
    email: "",
    user_group: "",
    avatar: "",
  });
  //校验密码与确认密码不一致
  let repeatValidate = (rule, value, callback) => {
    if (value !== form.value.password) {
      callback(new Error("两次输入密码不一致!"));
    } else {
      callback();
    }
  };
  let ruleFormRef = ref(null);
  let form_sub = ref({});
  let rules = ref({
    username: [
      {
        required: true,
        message: "账号不能为空",
        trigger: "blur",
      },
      {min: 5, max: 16, message: "用户名必须是5-16位字符", trigger: "blur"},
    ],
    nickname: [
      {
        required: true,
        message: "昵称不能为空",
        trigger: "blur",
      },
      {min: 2, max: 12, message: "用户名必须是2-12位字符", trigger: "blur"},
    ],
    user_group: [
      {
        required: true,
        message: "身份不能为空",
        trigger: "blur",
      },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址 例：test@test.com!",
        trigger: ["blur", "change"],
      },
    ],
    password: [
      {
        pattern: /^\S{5,16}$/,
        required: true,
        message: "密码 5 到 16 个字符",
        trigger: "blur",
      },
    ],
    avatar: [
      {
        required: true,
        message: "请上传头像",
        trigger: "blur",
      },
    ],
    confirm_password: [
      {
        required: true,
        message: "请再输入一遍密码",
        trigger: "blur",
      },
      {
        min: 5,
        max: 16,
        message: "长度应在 5 到 16 个字符",
        trigger: "blur",
      },
      {validator: repeatValidate, trigger: "blur"},
    ],
  });
  let list_user_group = ref([]);

  // 上传图
  let uploadimg = (param) => {
    uploadFile(param.file, "avatar");
  };
  /**
   * 上传图
   * @param {Object} file 文件对象
   * @param {key} 保存键名
   */
  const uploadFile = (file, key = "img") => {
    var formobj = new FormData(); // FormData 对象
    formobj.append("file", file); // 文件对象
          $upload(url_upload.value, formobj, function (json) {
      console.log(json);
      if (json) {
        form.value[key] = json.result.url;
        console.log(form.value[key]);
      } else {
        ElMessage.error("上传失败！");
      }
    });
  };
  /**
   * 上传文件
   * @param {String} url 请求地址
   * @param {Object} body 请求参数
   * @param {Funciton} func 回调函数，可以为空，为空则采用await返回值
   * @return {Object} 返回请求结果
   */
  let $upload = async (url, body, func) => {
    if (func) {
      // 如果回调函数存在, 则采用异步
            $post(url, body, {
        headers: {
          // "x-auth-token": token,
          "Content-Type": "multipart/form-data",
        },
      })
          .then((res) => {
            func(res);
          })
          .catch((res) => {
            func(res);
          });
    } else {
      // 否则采用同步
      var res = await $post(url, body, {
        headers: {
          "x-auth-token": token,
          "Content-Type": "multipart/form-data",
        },
      });
      return res;
    }
  };
  let user_group_flag = ref(null);
  //获取用户组权限
  let change_user_group = (user_group) => {
    window.localStorage.setItem("set_auth", "");
    //查询权限
          $get("/api/auth/get_list?user_group=" + user_group).then((json) => {
      store.commit("web/set_auth", []);
      // 判断查询结果
      if (json.result && json.result.list) {
        let auth = json.result.list;
        window.localStorage.setItem("set_auth", JSON.stringify(auth));
        store.commit("web/set_auth", auth);
      } else if (json.error) {
        ElMessage.error(json.error.message);
        console.error(json.error);
      }
    });
  };
  // 点击注册
  let Onsubmit = async () => {
    let valid = await ruleFormRef.value.validate();
    if (valid) {
      if(form.value.user_group=='注册用户'){
                                                                                                                                                                                                                                                                                                                            }
        if(form.value.user_group=='商家用户'){
                                                                                if($is_phone(form_sub.value.store_phone)){
          ElMessage.error("店铺电话格式不正确");
          ElMessage.error($is_phone(form_sub.value.store_phone));
          return;
        }
                                                                                                              }
                          const data = await $get("/api/user/count?username=" + form.value.username);
      if (data.result == 1) {
        ElMessage.error("用户已存在!");
      } else if (data.result == 0) {
        // 提交表单
        const res = await $post("/api/user/register", form.value);
        if (form.value) {
          const shallowCopy = Object.assign({},form_sub.value,form.value);
          Object.keys(shallowCopy).forEach((item) => {
            if (shallowCopy[item] === "" || shallowCopy[item] === null || shallowCopy[item].length === 0) {
              delete shallowCopy[item];
            }
          });
          const data_get_obj = await $get("/api/user/get_obj", {
            username: shallowCopy.username,
            nickname: shallowCopy.nickname,
            user_group: shallowCopy.user_group
          });
          let formObj=null;
          let ress=null;
          let url = null;
            if(shallowCopy.user_group=='注册用户'){
            formObj = {
                          membership_card_number: shallowCopy.membership_card_number,
                                real_name: shallowCopy.real_name,
                                user_gender: shallowCopy.user_gender,
                                user_age: shallowCopy.user_age,
                                user_tags: shallowCopy.user_tags,
                                user_preferences: shallowCopy.user_preferences,
                                description_and_explanation: shallowCopy.description_and_explanation,
                                document_information: shallowCopy.document_information,
                                user_photo: shallowCopy.user_photo,
                                personal_works: shallowCopy.personal_works,
                                user_remarks: shallowCopy.user_remarks,
                        user_id: data_get_obj.result.obj.user_id,
            };
            url = "/api/registered_user/add";
          }
              if(shallowCopy.user_group=='商家用户'){
            formObj = {
                          merchant_name: shallowCopy.merchant_name,
                                person_in_charge: shallowCopy.person_in_charge,
                                store_phone: shallowCopy.store_phone,
                                store_address: shallowCopy.store_address,
                                registered_capital: shallowCopy.registered_capital,
                                number_of_employees: shallowCopy.number_of_employees,
                        user_id: data_get_obj.result.obj.user_id,
            };
            url = "/api/merchant_users/add";
          }
                              ress = await $post(url, formObj);
          if (ress.result == 1) {
            ElMessage.success("注册/Register成功");
            setTimeout(() => {
              router.push("/");
            }, 1000);
          } else {
            ElMessage.error(ress.error.message);
          }
        }
      }
    } else {
      ElMessage.error(msg);
    }
  };
  // 获取用户组
  let get_user_group = async () => {
    let res = await $get(
        "/api/user_group/get_list?register_min=1&register_max=2"
    );
    if (res.result && res.result.list) {
      var list = [];
      var lt = res.result.list;
      lt.map((o) => {
        list.push(o.name);
      });
      list_user_group.value = list;
    } else if (res.error) {
      ElMessage.error(res.error.message);
    }
  };
  onMounted(() => {
    get_user_group();
    change_user_group("游客");
  });
</script>

<style scoped lang="less">
  .register_wrap {
    position: relative;
    height: 100%;
    background-image: url("../assets/images/bg.jpg");
    background-size: 100% 100%;
    .card-wrapper {
      z-index: 999;
      background: white;
      width: 900px;
      height: 700px;
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
      bottom: 0;
      display: flex;
      margin: auto;
	  overflow-y: auto;
      .left {
        width: 400px;
        background-image: url("../assets/images/bg.jpg");
      }
      .right {
        margin: 20px 0;
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        align-items: center;
  
        .title {
          font-size: 34px;
          // color: #4caaa2;
        }
        .login-form {
          .input {
            width: 270px;
          }
        }
        .button-wrapper {
          text-align: center;
        }
      }
    }
  }
</style>
